<template>
  <m-container class="confirm-in">
    <out-work-top-pallet-code :palletCode="form.palletCode" />
    <m-cell-group weight="label" :border="false">
      <m-cell label="派送方式" size="xs" />
      <m-cell title="派送方式" size="xs">
        <view class="center" slot="center" style="margin-left: -30rpx">
          <m-radio-group inline v-model="form.deliveryType">
            <m-radio :label="+val" v-for="(key, val) in deliveryTypeMap" :key="val">{{ key }} </m-radio>
          </m-radio-group>
        </view>
      </m-cell>
    </m-cell-group>
    <m-cell-group weight="label" :border="false">
      <m-cell label="当前站点" size="xs" />
      <m-cell title="地标码" size="xs">
        <view class="center" slot="center">
          <m-text :line="1"> {{ form.deliveryStartCode }}</m-text>
          <m-button
            shape="round"
            background="#fff"
            size="md"
            plain
            height="76rpx"
            width="220rpx"
            @click="handleScanStartCode"
          >
            扫描地标码
          </m-button>
        </view>
      </m-cell>
    </m-cell-group>
    <m-cell-group weight="label" :border="false" class="selectIms">
      <m-cell label="选择仓库" size="xs" />
      <m-cell size="xs">
        <view class="center" slot="center" style="padding-left: 0">
          <m-radio-group inline v-model="form.imsId" @change="handleChangeIms">
            <m-radio :label="+item.value" v-for="(item, index) in getImsOptions" :key="index">
              {{ item.label }}
            </m-radio>
          </m-radio-group>
        </view>
      </m-cell>
    </m-cell-group>
    <m-cell-group weight="label" size="sm" :border="false">
      <m-cell label="目标站点" size="xs" />
      <m-cell size="xs">
        <view class="row" slot="center" style="margin-right: -8rpx">
          <view class="row_radio">
            <m-radio-group inline v-model="form.type" @change="handleChangeType">
              <m-radio-button :label="1">
                <u-image width="60rpx" height="60rpx" src="@/static/jcz1.png" v-if="form.type === 1" />
                <u-image width="60rpx" height="60rpx" src="@/static/jcz.png" v-else />
                <text>检测站</text>
              </m-radio-button>
              <m-radio-button :label="2" @click.stop="handleChangeType">
                <u-image width="60rpx" height="60rpx" src="@/static/mt2.png" v-if="form.type === 2" />
                <u-image width="60rpx" height="60rpx" src="@/static/mt.png" v-else />
                <text>码头</text>
              </m-radio-button>
              <m-radio-button :label="3" style="margin-right: 0" @click.stop="handleChangeType">
                <u-image width="60rpx" height="60rpx" src="@/static/lk3.png" v-if="form.type === 3" />
                <u-image width="60rpx" height="60rpx" src="@/static/lk.png" v-else />
                <text>立库</text>
              </m-radio-button>
            </m-radio-group>
          </view>
          <view v-if="form.type === 2" class="text">
            码头具体位置：{{ form.imsText }}/{{ form.deliveryTargetCodeTxt }}
          </view>

          <m-radio-group inline v-model="value" @change="handleChange" v-else>
            <m-radio :label="item.value" v-for="(item, index) in map[form.type]" :key="index" @click="handleRadioClick">
              {{ item.name }}
            </m-radio>
          </m-radio-group>
        </view>
      </m-cell>
    </m-cell-group>

    <in-work-layer v-model="show" :id="form.imsId" @confirm="handleDeliveryTargetCode" />

    <in-work-layer-station
      :pallet-code="form.palletCode"
      :id="form.imsId"
      v-model="show1"
      @confirm="handleClickConfirmTargetCode"
    />

    <m-fixed>
      <m-button width="100%" size="xl" @click="handleClickConfirm" :loading="loading" :disabled="loading"
        >确认回库</m-button
      >
    </m-fixed>
  </m-container>
</template>

<script>
const barcodeModel = uni.requireNativePlugin('iData-BarcodePlugin-BarcodeModule')
const globalEvent = uni.requireNativePlugin('globalEvent')
import { showModal } from '@/hooks'
import { mapState } from 'vuex'
import { imsDetectionStation, getIms } from '@/api/modules/in-work'
import { storageLocationDetails, toStorageLocation } from '@/api/modules/out-work'
import { deliveryTypeMap } from '@/utils/constant'
import { isAppPlus } from '@/utils/platform'
import { router } from '@/router'
import { map } from '@/utils/constant'

export default {
  data() {
    return {
      value: 1,
      show: false,
      show1: false,
      loading: false,
      form: {
        deliveryType: 2,
        deliveryStatus: 0,
        deliveryStartCode: isAppPlus
          ? ''
          : 'S' +
            Math.floor(Math.random() * 1000000)
              .toString()
              .padStart(6, '0'),
        deliveryTargetCode: '',
        type: 1,
        imsId: '',
      },
      map: {
        1: [],
        3: [
          { name: '系统分配', value: 1 },
          { name: '人工分配', value: 2 },
        ],
      },
      targetCode: '',
      deliveryTypeMap,
      arr: [],
    }
  },
  computed: {
    ...mapState({
      imsList: (state) => state.cache.imsList,
    }),
    getIsSystemDistributor() {
      return [3, 2].includes(this.form.type) && [2].includes(this.value)
    },
    getImsOptions() {
      const data = this.arr
        .map((item) => {
          const curr = this.imsList.arr.find((it) => it.value === +item)
          return curr || null
        })
        .filter((item) => Boolean(item))
      return data
    },
  },
  async onLoad(options) {
    this.arr = options.arr.split(',')
    this.fetchData(options.palletCode, this.getImsOptions[0].value)
    barcodeModel.initScan()
    globalEvent.addEventListener('iDataBarcodeEvent', ({ barcode }) => {
      if (this.$Router.currentRoute.name !== 'ConfirmReturnHouse') {
        return
      }

      if (barcode.startsWith('S') && barcode.length === 12) {
        this.form.deliveryStartCode = barcode
      } else {
        uni.showToast({
          title: '请扫描正确的地标码',
          icon: 'none',
        })
      }
    })
  },
  onUnload() {
    barcodeModel.closeScan()
  },

  methods: {
    async fetchData(palletCode, imsId) {
      const {
        data: { defaultTargetStation },
      } = await getIms(imsId)

      const { data: list } = await storageLocationDetails({
        palletCode,
      })

      this.form = {
        palletCode,
        ...this.form,
        list,
        imsId,
        type: defaultTargetStation,
      }

      this.handleChangeType()
      const { rows } = await imsDetectionStation({
        pageNum: 1,
        pageSize: 1000,
      })

      this.map[1] = rows.map((item) => ({ name: item.detectionStationCode, value: item.detectionStationId }))
      this.value = this.map[1][0].value
      this.targetCode = this.map[1][0].value

      this.form = {
        ...this.form,
        deliveryTargetCode: '',
        stationId: null,
        stationCode: null,
        stackNo: null,
        levelNo: null,
        locationNo: null,
      }
      this.handleChange()
    },
    handleChangeIms(e) {
      this.fetchData(this.form.palletCode, e)
    },
    handleDeliveryTargetCode(e) {
      this.form.deliveryTargetCode = e.code
      this.form.deliveryTargetCodeTxt = e.codeTxt
      this.form.imsText = e.imsText
    },
    handleScanStartCode() {
      barcodeModel.scanStart((ret) => {
        console.log(7)
      })
    },
    handleClickConfirmTargetCode(e) {
      this.form = {
        ...this.form,
        ...e,
        deliveryTargetCode: e.stationCode,
      }

      this.map[3][1].name = `人工分配 ${e.stackNo}-${e.levelNo}-${e.locationNo}`
    },
    handleClickConfirm() {
      this.loading = true
      try {
        if (this.form.deliveryStartCode === '') {
          uni.showToast({
            title: '请扫描地标码',
            icon: 'none',
          })
          this.loading = false
          return
        } else if (this.getIsSystemDistributor && this.form.deliveryTargetCode === '') {
          uni.showToast({
            title: '请选择目标位置',
            icon: 'none',
          })
          this.loading = false
          return
        }

        showModal({
          title: '回库提示',
          content: '请问您确认是否要回库？',
          showCancelButton: true,
          slot: true,
          confirm: async () => {
            const params = {
              ...this.form,
              list: this.list,
              toStorageLocationType: 2,
            }
            await toStorageLocation(params)
            uni.showToast({
              title: '回库成功',
              icon: 'none',
              duration: 2000,
            })
            this.loading = false
            router.replaceAll({
              name: 'Index',
            })
          },
          cancel: () => {
            this.loading = false
          },
        })
      } catch (e) {
        this.loading = false
      }
    },
    handleChangeType() {
      if (this.form.type === 2) {
        this.show = true
        this.form.deliveryTargetCode = ''
      } else if (this.form.type === 3 && this.value === 2) {
        this.show1 = true
        this.form.deliveryTargetCode = ''
      } else if (this.form.type === 1) {
        this.value = this.targetCode
        this.form.deliveryTargetCode = this.value
      }
    },
    handleRadioClick(e) {
      if (this.form.type === 3 && e === 2) {
        this.show1 = true
      }
    },
    handleChange() {
      if (this.form.type === 1) {
        this.form.deliveryTargetCode = this.value
      } else if (this.form.type === 3) {
        this.form = {
          ...this.form,
          stationId: null,
          stationCode: null,
          stackNo: null,
          levelNo: null,
          locationNo: null,
        }
        this.map[3][1].name = `人工分配`
      }

      this.handleChangeType()
    },
  },
}
</script>

<style lang="scss" scoped>
.confirm-in {
  .center {
    padding-left: 80rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .row_radio {
    margin-bottom: 10rpx;
    .radio {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 33.3%;
      background: #fff;
      border-color: #d7dce0;
      color: #748da7;
      &--checked {
        border-color: #248dfa;
        color: #248dfa;
      }
      text {
        margin-top: 19rpx;
        font-size: 28rpx;
      }
    }
  }
  .selectIms {
    ::v-deep {
      .radio-group__content {
        flex-wrap: wrap;
        justify-content: space-between;
      }
      .radio--inline {
        margin-bottom: 10px;
        margin-right: 0;
      }
    }
  }

  .text {
    text-align: center;
    font-size: 25rpx;
    color: #00a8f0;
    font-weight: bold;
  }
}
</style>
